<template>
  <div class="shoppingCart">
    <div class="wrapper_1200">
      <div class="title wrapper_1200">
        <nuxt-link class="home" to="/">{{$t('page.goodsDetail.home')}} ></nuxt-link>
        {{$t('page.goodsDetail.cart')}}
       </div>
      <div class="cartList" v-if="cartValid.length">
        <div class="header acea-row row-middle">
          <div class="allSelect acea-row row-center-wrapper" @click="allChecked">
            <div class="checkbox-wrapper">
              <label class="well-check">
                <input
                  type="checkbox"
                  name=""
                  value=""
                  :checked="isAllSelect"
                  @click="allChecked"
                />
                <i class="icon"></i>
                <span class="checkAll">{{$t('page.goodsAddcart.selectAll')}}</span>
              </label>
            </div>
          </div>
          <div class="info acea-row row-center-wrapper"> {{$t('page.goodsAddcart.info')}}</div>
          <div class="price acea-row row-center-wrapper">{{$t('page.goodsList.price')}}</div>
          <div class="num acea-row row-center-wrapper">{{$t('page.goodsDetail.num')}}</div>
          <div class="money acea-row row-center-wrapper"> {{$t('page.orderPayStatus.payPrice')}}</div>
          <div class="operate acea-row row-center-wrapper">{{$t('page.goodsAddcart.fonctionner')}}</div>
        </div>
        <div class="body">
          <div v-for="(item, index) in cartValid" :key="index">
            <div class="store-info acea-row">
              <div class="storeAllSelect">
                <div class="checkbox-wrapper">
                  <label class="well-check">
                    <input
                      type="checkbox"
                      name=""
                      value=""
                      :checked="item.checked"
                      @click="storeChecked(item,index)"
                    />
                    <i class="icon"></i>
                    <span class="checkAll">{{ item.mer_name }}</span>
                    <span class="trader" v-if="item.is_trader">{{$t('page.store.selfSupport')}}</span>
                  </label>
                </div>
              </div>
            </div>
            <div class="storeCartList">
              <div class="item acea-row row-middle" v-for="(itemn, indexn) in item.list" :key="indexn">
                <div class="allSelect acea-row row-center-wrapper">
                  <div class="checkbox-wrapper">
                    <label class="well-check">
                      <input
                        type="checkbox"
                        name=""
                        value=""
                        :checked="itemn.checked"
                        @click="switchSelect(index,indexn)"
                      />
                      <i class="icon"></i>
                    </label>
                  </div>
                </div>
                <div class="info acea-row row-middle">
                  <div class="pictrue">
                    <img v-if="itemn.productAttr && itemn.productAttr.image" :src='itemn.productAttr.image'>
                    <img v-else :src='itemn.product.image'>
                  </div>
                  <div class="text">
                    <div class="name line2">{{itemn.product['store_name_'+lang] ?itemn.product['store_name_'+lang] : itemn.product.store_name }}</div>
                    <div class="infor" v-if="itemn.productAttr">{{$t('page.goodsAddcart.attribute')}}：{{ itemn.productAttr.sku || "" }}</div>
                  </div>
                </div>
                <div class="price acea-row row-center-wrapper" v-if="itemn.productAttr">${{ itemn.productAttr.price || "" }}</div>
                <div class="num acea-row row-center-wrapper">
                  <div class="iconfont icon-shangpinshuliang-jian" :class="itemn.numSub?'grey':''"
                       @click.prevent="reduce(itemn)"></div>
                  <!--<div class="numCon">{{item.cart_num}}</div>-->
                  <input class="numCon" v-model="itemn.cart_num" @input="inputNum(itemn)"/>
                  <button :disabled="itemn.numAdd" class="iconfont icon-shangpinshuliang-jia"
                          :class="itemn.numAdd ?'grey':''" @click.prevent="plus(itemn)"></button>
                </div>
                <!-- <div class="money acea-row row-center-wrapper font-color">${{comsys.Mul(item.truePrice,item.cart_num)}}</div> -->
                <div class="money acea-row row-center-wrapper font-color" v-if="itemn.productAttr">
                  ${{ itemn.productAttr.price ? itemn.productAttr.price * itemn.cart_num : "" }}
                </div>
                <div class="operate acea-row row-center-wrapper" @click="delgoods(itemn)"><span
                  class="iconfont icon-shanchu"></span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="cartList invalid" v-if="cartInvalid.length">
        <div class="body">
          <div class="item acea-row row-middle" v-for="(item, index) in cartInvalid" :key="index">
            <div class="allSelect acea-row row-center-wrapper">
              <div class="checkbox-wrapper">
                <label class="well-check" style="color: #d2d2d2;">
                  {{$t('page.goodsAddcart.failureGoods')}}
                </label>
              </div>
            </div>
            <div class="info acea-row row-center-wrapper">
              <div class="pictrue">
                <img :src="item.productAttr.image" v-if="item.productAttr">
                <img :src="item.product.image" v-else>
              </div>
              <div class="text">
                <div class="name line2 grey">{{ item.product['store_name_'+lang] ?item.product['store_name_'+lang] : item.product.store_name }}</div>
                <div class="infor" v-if="item.productAttr">{{$t('page.goodsAddcart.attribute')}}：{{ item.productAttr.sku }}</div>
              </div>
            </div>
            <div class="price acea-row row-center-wrapper grey">${{ item.product.price }}</div>
            <div class="num acea-row row-center-wrapper">
              <div class="iconfont icon-shangpinshuliang-jian grey"></div>
              <div class="numCon grey">{{ item.cart_num }}</div>
              <div class="iconfont icon-shangpinshuliang-jia grey"></div>
            </div>
            <div class="money acea-row row-center-wrapper font-color grey" >
              ${{ item.product.price * item.cart_num }}
            </div>
            <div class="operate acea-row row-center-wrapper" @click="delgoods(item)"><span
              class="iconfont icon-shanchu"></span></div>
          </div>
        </div>
      </div>
      <div class="footer acea-row row-between-wrapper" v-if="cartValid.length || cartInvalid.length">

        <div class="num">
          <div class="allSelect" @click="allChecked">
            <div class="checkbox-wrapper">
              <label class="well-check">
                <input
                  type="checkbox"
                  name=""
                  value=""
                  :checked="isAllSelect"
                  @click="allChecked"
                />
                <i class="icon"></i>
                <span class="checkAll">{{$t('page.goodsAddcart.selectAll')}}</span>
              </label>
            </div>
          </div>
          {{$t('page.goodsDetail.choose')}} {{ cartCount }} {{$t('page.orderDetails.item')}}</div>
        <div class="acea-row row-middle">
          <div class="total">{{$t('page.users.orderConfirm.total')}}：<span class="font-color">${{ countmoney }}</span></div>
          <div class="bnt bg-color" @click="subOrder">{{$t('page.goodsDetail.settle')}}</div>
        </div>
      </div>
      <div class="noCart" v-if="!cartValid.length && !cartInvalid.length">
        <div class="pictrue"><img src="../assets/images/noCart1.png"></div>
        <div class="tip">{{$t('page.index.empty')}} </div>
        <nuxt-link to="/" class="goIndex">{{$t('page.index.continueshopping')}}</nuxt-link>
      </div>
    </div>
  </div>
</template>

<script>
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
const CHECKED_IDS = "cart_checked";
export default {
  name: "shoppingCart",
  auth: "guest",
  data() {
    return {
      cartValid: [],
      cartInvalid: [],
      isAllSelect: false,
      countmoney: 0,//购物车产品总价；
      cartNum: 0,
      cartCount: '',
      lang:'',
    }
  },
  fetch({store}) {
    store.commit('isHeader', true);
    store.commit('isFooter', true);
  },
  head() {
    return {
      title: this.$t('page.goodsDetail.cart') + "-" + this.$store.state.titleCon
    }
  },
  beforeMount() {
    this.lang = this.$cookies.get('locale') || 'en';
    if(this.lang === "zh-Hant"){
      this.lang = 'tw'
    }
    this.getCartList();
  },
  mounted() {
    document.body.setAttribute("style", "background:#ffffff");
  },
  beforeDestroy() {
    document.body.removeAttribute("style");
  },
  methods: {
    inputNum(item) {
      let that = this;
      item.cart_num = parseInt(item.cart_num) >= item.trueStock ? item.trueStock : item.cart_num;
      item.cart_num = parseInt(item.cart_num) <= 1 || isNaN(parseInt(item.cart_num)) ? 1 : item.cart_num;
      that.countMoney();
      let conNum = 0;
      that.cartValid.forEach(item => {
        item.list.forEach(i => {
            conNum += parseInt(i.cart_num)
        });
      });
      that.cartInvalid.forEach(item => {
        item.list.forEach(i => {
          conNum += parseInt(i.cart_num)
        });
      });
      that.$store.commit('cartNum', conNum);
      that.syncCartNum(item);
    },
    //立即下单；
    subOrder: function () {
      let that = this,
        list = that.cartValid,
        id = [];
      list.forEach(function (val) {
        val.list.forEach(function (val) {
          if (val.checked === true) {
            id.push(val.cart_id);
          }
        })
      });
      if (id.length === 0) {
        that.$message.error(this.$t('page.index.pleaseselectaproduct'));
        return;
      }
      this.$router.push({path: '/order_confirm?cartId=' + id.join(',')});
    },
    //删除商品；
    delgoods: function (item) {
      let that = this;
      let checkedIds = that.$cookies.get(CHECKED_IDS) || [];
      let index = checkedIds.indexOf(item.id);
      if(index>-1){
        checkedIds.splice(index, 1);
      }
      that.$axios.post('/api/user/cart/delete', {cart_id: [item.cart_id.toString()]}).then(res => {
        that.$message.success(this.$t('message.login.delSU'));
        that.gainCount();
        that.getCartList();
        that.countMoney();
      })
    },
    gainCount: function() {
      let that = this;
      that.$axios.get('/api/user/cart/count').then(res=>{
        that.$store.commit('cartNum', res.data[0].count || 0);
      });
    },
    getCartList() {
      let that = this;
      that.$axios.get('/api/user/cart/lst').then(res => {
        that.cartValid = res.data.list;
        that.cartInvalid = res.data.fail;
        let checked = this.$cookies.get(CHECKED_IDS) || [];
        that.cartValid.forEach(cart => {
          cart.list.forEach(cartItem => {
            if (checked.length) {
              cartItem.checked = checked.indexOf(cartItem.cart_id) > -1;
            } else {
              cartItem.checked = true;
            }
            if (cartItem.cart_num == 1) {
              cartItem.numSub = true;
            } else {
              cartItem.numSub = false;
            }
            if (cartItem.cart_num == cartItem.productAttr.stock) {
              cartItem.numAdd = true;
            } else {
              cartItem.numAdd = false;
            }
          })
        });
        that.storeAllChceked();
        that.countMoney();
      })
    },
    //加
    plus: function (goods, index) {
      let that = this;
      goods.cart_num++;
      if (goods.hasOwnProperty('productAttr') && goods.cart_num > goods.productAttr.stock) {
        goods.cart_num = goods.productAttr.stock;
        goods.numAdd = true;
        goods.numSub = false;
        return
      } else {
        goods.numAdd = false;
        goods.numSub = false;
      }
      that.$store.commit('cartNum', that.$store.state.cartnumber + 1);
      that.countMoney();
      that.syncCartNum(goods);
    },
    //减
    reduce: function (goods) {
      let that = this;
      let status = false;
      if (goods.cart_num <= 1) {
        goods.cart_num = 1;
        goods.numSub = true;
        status = true;
      } else {
        goods.cart_num = Number(goods.cart_num) - 1
        this.cartTotalCount = Number(that.cartTotalCount) - 1;
        goods.numSub = false;
        goods.numAdd = false;
        that.$store.commit('cartNum', that.$store.state.cartnumber - 1);
        if (goods.cart_num <= 1) {
          goods.numSub = true;
        }
      }
      that.countMoney();
      that.syncCartNum(goods);
    },
    syncCartNum(cart) {
      if (!cart.sync)
        cart.sync = window.debounce(() => {
          this.$axios.post('/api/user/cart/change/' + cart.cart_id, {
            cart_num: Math.max(cart.cart_num, 1) || 1
          }).then(res => {
          }).catch(err =>{
            cart.cart_num--;
            this.$store.commit('cartNum', this.$store.state.cartnumber - 1);
            this.$message.error(err);
          })
        }, 500);
      cart.sync();
    },
    //单选
    switchSelect: function (index, indexn) {
      let that = this,
        cart = that.cartValid[index]['list'][indexn];
      cart.checked = !cart.checked;

      let len = 0;
      let selectnum = [];
      for (let j = 0; j < that.cartValid.length; j++) {
        for (let k = 0; k < that.cartValid[j]['list'].length; k++) {
          len++;
          if (that.cartValid[j]['list'][k].checked === true) {
            selectnum.push(true);
          }
        }
      }
      that.isAllSelect = selectnum.length === len;
      that.$set(that, "cartValid", that.cartValid);
      that.storeAllChceked();
      that.$set(that, "isAllSelect", that.isAllSelect);
      that.countMoney();
    },
    /**判断单个店铺是不是全选 */
    storeAllChceked: function () {
      let selectnum, selectAllnum = [], checknum = 0;
      let that = this;
      for (let j = 0; j < that.cartValid.length; j++) {
        selectnum = [];
        for (let k = 0; k < that.cartValid[j]['list'].length; k++) {
          checknum++;
          if (that.cartValid[j]['list'][k].checked) {
            selectnum.push(true);
            selectAllnum.push(true);
          } else {
            selectnum.length - 1;
            selectAllnum.length - 1;
          }
          that.cartValid[j]['checked'] = selectnum.length === that.cartValid[j]['list'].length;
          that.isAllSelect = selectAllnum.length === checknum;
          that.$set(that, "cartValid", that.cartValid);
        }
      }
    },
    //单个店铺商品全选
    storeChecked: function (item, index) {
      let that = this;
      item.checked = !item.checked;
      that.cartValid[index]['list'].forEach(cart => {
        cart.checked = item.checked;
      });
      that.$set(that, "cartValid", that.cartValid);
      that.storeAllChceked();
      that.countMoney();
    },
    //全选
    allChecked: function () {
      let that = this;
      let selectAllStatus = that.isAllSelect;
      selectAllStatus = !selectAllStatus;
      that.cartValid.forEach(cart => {
        cart.checked = selectAllStatus;
        cart.list.forEach(cartItem => {
          cartItem.checked = selectAllStatus;
        });
      });
      that.$set(that, "cartValid", that.cartValid);
      that.$set(that, "isAllSelect", selectAllStatus);
      that.countMoney();
    },
    //总共价钱；
    countMoney: function () {
      let that = this;
      let carmoney = 0, totalNum = 0;
      let array = that.cartValid;
      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array[i]['list'].length; j++) {
          if (array[i]['list'][j].checked === true) {
            carmoney = this.comsys.Add(carmoney, this.comsys.Mul(array[i]['list'][j].cart_num, array[i]['list'][j]['productAttr']['price']));
            totalNum += array[i]['list'][j].cart_num
          }
        }
      }
      this.cartCount = totalNum
      that.countmoney = carmoney;
      this.countNum();
    },
    countNum() {
      let num = 0;
      let checkedList = []
      this.cartValid.forEach(item => {
        item.list.forEach(cart => {
          if (cart.checked) {
            checkedList.push(cart.cart_id);
            num++;
          }
        })
      })
      setTimeout(() => {
        this.$cookies.set(CHECKED_IDS, checkedList);
      }, 300);
      this.cartNum = num;
    }
  }
}
</script>

<style scoped lang="scss">
.grey {
  color: #D0D0D0 !important;
}
.shoppingCart {
  cursor: pointer;
  background-color: #F9F9F9;
  .noCart {
    text-align: center;
    .pictrue {
      width: 274px;
      height: 174px;
      margin: 111px auto 0 auto;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .tip {
      font-size: 14px;
      color: #969696;
      margin-top: 20px;
    }
    .goIndex {
      width: 90px;
      height: 35px;
      border: 1px solid #282828;
      border-radius: 6px;
      text-align: center;
      line-height: 35px;
      font-size: 14px;
      color: #282828;
      margin: 24px auto 100px auto;
      display: block;
    }
  }
  .title {
    height: 59px;
    line-height: 59px;
    color: #999999;
    .home {
      color: #282828;
    }
  }
  .cartList {
    .header {
      height: 54px;
      background: #EEEEEE;
    }
    .allSelect {
      width: 100px;
      position: relative;
      .checkAll {
        margin-left: 30px;
      }
    }
    .info {
      width: 400px;
      padding-left: 30px;
    }
    .price {
      width: 215px;
    }
    .num {
      width: 150px;
    }
    .money {
      width: 270px;
    }
    .body {
      .storeCartList {
        border: 1px solid #EFEFEF;
        background-color: #fff;
      }
      .item {
        & ~ .item {
          border-top: 1px dotted #E2E2E2;
        }
        height: 170px;
        .info {
          .pictrue {
            width: 90px;
            height: 90px;
            margin-right: 14px;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .text {
            width: 264px;
            .infor {
              margin-top: 10px;
              font-size: 12px;
              color: #D0D0D0;
            }
          }
        }
        .price {
          font-size: 16px;
        }
        .num {
          .iconfont {
            width: 40px;
            height: 36px;
            line-height: 36px;
            border: 1px solid #D3D3D3;
            text-align: center;
            color: #707070;
            background-color: #fff;
          }
          .numCon {
            width: 54px;
            height: 36px;
            border: 0;
            border-top: 1px solid #D3D3D3;
            border-bottom: 1px solid #D3D3D3;
            font-size: 15px;
            color: #5A5A5A;
            text-align: center;
            line-height: 36px;
            outline: none;
          }
        }
        .money {
          font-size: 16px;
        }
        .operate {
          color: #D0D0D0;
          .iconfont {
            font-size: 20px;
          }
        }
      }
    }
  }
  .store-info {
    padding: 0 20px;
    height: 73px;
    align-items: center;
    .checkbox-wrapper {
      padding-left: 28px;
    }
    .trader {
      display: inline-block;
      color: #fff;
      font-size: 12px;
      background-color: #E93323;
      width: 32px;
      height: 17px;
      line-height: 17px;
      text-align: center;
      border-radius: 2px;
      margin-left: 7px;
    }
  }
  .invalid {
    margin-top: 20px;
    border-top: 1px solid #EFEFEF;
  }
  .footer {
    height: 82px;
    background: #EEEEEE;
    margin-top: 60px;
    padding-left: 30px;
    margin-bottom: 30px;
    .allSelect {
      width: 100px;
      position: relative;
      display: inline-block;
      .checkAll {
        margin-left: 30px;
      }
    }
    .total {
      font-size: 16px;
      .font-color {
        font-size: 22px;
        font-weight: bold;
      }
    }
    .bnt {
      width: 160px;
      height: 82px;
      text-align: center;
      line-height: 82px;
      font-size: 18px;
      color: #fff;
      margin-left: 30px;
    }
  }
}
</style>
